//
// Created by EmFi on 2023/5/12.
//

#ifndef DBMS_CSVUTIL_H
#define DBMS_CSVUTIL_H

#include <string>
#include <list>
#include <fstream>
#include <iostream>
#include <sstream>
#include "../define.h"
#include "../Database/Point.h"

using namespace std;

class CsvUtil {
public:
    static list<Point> read(const string& fn) {
        list<Point> list;

        ifstream csv_file(fn, ios::in);

        if (!csv_file.is_open()) {
            cout << "Error: can not _open file \"" << fn  << "\"." << endl;
            exit(1);
        } else {
            string line;
            string word;

            // 读标题行
            getline(csv_file, line);

            istringstream sin;

            // 读数据行
            while (getline(csv_file, line)) {
                sin.clear();
                sin.str(line);

                Point p;
                int i = 0;
                while (getline(sin, word, ',')) {
                    if (!word.empty()) {
                        p.push(stod(word));
                    } else {
                        p.push(NULL);
                    }
                    i++;
                }
                if (i < 4) {
                    p.push(NULL);
                }

                list.push_back(p);
            }
            csv_file.close();
        }

        return list;
    }
};


#endif //DBMS_CSVUTIL_H
